package com.cskaoyan.controller.mall;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.mall.category.Category;
import com.cskaoyan.bean.mall.category.level;
import com.cskaoyan.service.mall.CategoryService;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.ValidationUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("admin/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @RequiresPermissions("admin:category:list")
    @GetMapping("list")
    public BaseRespVo queryCategory() {
        List<Category> categoryList = categoryService.queryCategory();
        return BaseRespVo.ok(PageDataVo.ok(categoryList));
    }

    @RequiresPermissions("admin:category:list")
    @GetMapping("l1")
    public BaseRespVo getCategory() {
        List<Category> categoryList = categoryService.queryCategory();
        LinkedList<level> l1s = new LinkedList<>();
        for (Category category : categoryList) {
                l1s.add(new level(category.getName(), category.getId()));
        }
        return BaseRespVo.ok(PageDataVo.ok(l1s));
    }

    @RequiresPermissions("admin:category:create")
    @PostMapping("create")
    public BaseRespVo createCategory(@RequestBody@Validated Category category, BindingResult bindingResult) {
        ValidationUtil.valid(bindingResult);
        Category newCategory = categoryService.createCategory(category);
        if (newCategory == null) return BaseRespVo.error("添加失败");
        return BaseRespVo.ok(newCategory);
    }

    @RequiresPermissions("admin:category:delete")
    @PostMapping("delete")
    public BaseRespVo deleteCategory(@RequestBody@Validated Category category,BindingResult bindingResult){
        ValidationUtil.valid(bindingResult);
        int code=categoryService.deleteCategory(category);
        if (code== Constant.SUCCESS)return BaseRespVo.ok();
        return BaseRespVo.error("存在子分类，删除失败,请将子分类删除后重试");
    }

    @RequiresPermissions("admin:category:create")
    @PostMapping("update")
    public BaseRespVo updateCategory(@RequestBody@Validated Category category,BindingResult bindingResult){
        ValidationUtil.valid(bindingResult);
       int code=categoryService.updateCategory(category);
       if (code==Constant.SUCCESS)return BaseRespVo.ok();
       return BaseRespVo.error();
    }
}
